package utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCutils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection>threadLocal = new ThreadLocal<Connection>();
    static {
        try {
//          之前写InputStream is =ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties pro = new Properties();
            pro.load(is);
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn(){
      Connection conn = threadLocal.get();
      if(conn==null){
          try {
              conn = dataSource.getConnection();
              threadLocal.set(conn);
              conn.setAutoCommit(false);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      return conn;
    }

//    @Test
//    public void test(){
//        Connection conn = getConn();
//        System.out.println(conn);
//    }
    public static  void  closeAndCommit(){
        Connection conn=threadLocal.get();
        if(conn!=null){
            try {
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //因为tomcat底层使用了数据库连接池，所以要Remove(),否则会报错
        threadLocal.remove();
    }
    public static void rollBack(){
        Connection conn=threadLocal.get();
        if(conn!=null){
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        threadLocal.remove();
    }
}

